package com.example.tianxi.yuexiuhhpatient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.Toast;
import android.view.View.OnClickListener;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Calendar;
import java.lang.String;
import java.io.File;
import android.provider.MediaStore;
import android.os.Environment;
import android.net.Uri;
import android.graphics.Bitmap;


public class PersonalInfoActivity extends Activity implements View.OnClickListener{

    private TextView back;
    private TextView title;


    private TextView name;
    private TextView sex;
    private TextView bir;
    private TextView tell;
    private TextView introduce;
    private ImageView photo;
    private JSONObject info;
    private String dataString;
    private RelativeLayout setPhoto;
    private RelativeLayout setName;
    private RelativeLayout setSex;
    private RelativeLayout setBir;
    private RelativeLayout setTel;
    private RelativeLayout setIntroduce;
    /*头像文件*/
    private static final String IMAGE_FILE_NAME = "temp_head_image.jpg";
    /*请求识别码*/
    private static final int CODE_GALLERY_REQUEST = 0Xa0;//本地
    private static final int CODE_CAMERA_REQUEST = 0Xa1;//相机
    private static final int CODE_RESULT_REQUEST = 0Xa2;//最终裁剪后的结果
    //裁剪后图片的宽和高,形成480*480的头像
    private static int outPut_X = 480;
    private static int outPut_Y = 480;
    private ImageView headImage = null;


    private boolean isChanged = false;//个人信息是否修改
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_info);
        Intent intent = getIntent();

        photo = (ImageView)findViewById(R.id.personal_photo);
        name = (TextView)findViewById(R.id.personal_name);
        sex = (TextView)findViewById(R.id.personal_sex);
        bir = (TextView)findViewById(R.id.personal_birth);
        tell = (TextView)findViewById(R.id.personal_phone);
        introduce = (TextView)findViewById(R.id.personal_introduce);

        name.setText(intent.getStringExtra("name"));
        sex.setText(intent.getStringExtra("sex"));
        bir.setText(intent.getStringExtra("birth"));
        tell.setText(intent.getStringExtra("tel"));
        introduce.setText(intent.getStringExtra("introduction"));

        title = (TextView)findViewById(R.id.title);
        title.setText("编辑个人信息");
        back = (TextView)findViewById(R.id.back);
        back.setText("返回");
        back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (isChanged) {
                    Intent intent1 = new Intent();
                    intent1.putExtra("name", name.getText().toString().trim());
                    intent1.putExtra("personInfo", dataString);
                    setResult(RESULT_OK, intent1);
                } else {
                    setResult(RESULT_CANCELED);
                }
                PersonalInfoActivity.this.finish();

            }
        });

        setPhoto = (RelativeLayout)findViewById(R.id.set_personalphoto);
        setName = (RelativeLayout)findViewById(R.id.set_personalname);
        setSex = (RelativeLayout)findViewById(R.id.set_personalsex);
        setBir = (RelativeLayout)findViewById(R.id.set_personalbirth);
        setTel = (RelativeLayout)findViewById(R.id.set_personalphone);
        setIntroduce = (RelativeLayout)findViewById(R.id.set_personalintroduce);

        clickListener listener = new clickListener();

        setName.setOnClickListener(this);
        setSex.setOnClickListener(this);
        setBir.setOnClickListener(this);
        setTel.setOnClickListener(this);

        setIntroduce.setOnClickListener(this);
    }

    class clickListener implements OnClickListener
    {
        Intent intent = new  Intent();
        @Override
        public void onClick(View view) {


        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.set_personalphoto:
                headImage = (ImageView) findViewById(R.id.personal_photo);
                headImage.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        final LinearLayout layout3 = (LinearLayout) getLayoutInflater().inflate(R.layout.edit_photo_dialog, null);
                        AlertDialog.Builder builder = new AlertDialog.Builder(PersonalInfoActivity.this);
                        builder.setIcon(null);
                        builder.setTitle("选择头像");
                        builder.setView(layout3);
                        builder.show();
                        //headImage = (ImageView) findViewById(R.id.personal_photo);
                        Button buttonLocal = (Button) layout3.findViewById(R.id.buttonLocal);
                        Button buttonCamera = (Button) layout3.findViewById(R.id.buttonCamera);


                        buttonLocal.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                choseHeadImageFromGallery();
                            }

                        });
                        buttonCamera.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                choseHeadImageFromCameraCapture();
                            }
                        });
                    }
                });


                break;







            case R.id.set_personalname:
                final LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.edit_name_dialog, null);

                //EditText tvname= (EditText)findViewById(R.id.edit_name);
                //final String n = tvname.getText().toString().trim();

                new AlertDialog.Builder(this)
                        .setIcon(null)
                        .setTitle("编辑姓名")
                        .setView(layout)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which){
                                EditText tvname= (EditText)layout.findViewById(R.id.edit_name);
                                final String n = tvname.getText().toString().trim();
                                name.setText(n);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create()
                        .show();
                break;
            case R.id.set_personalsex:
                //LinearLayout layout = (LinearLayout)getLayoutInflater().inflate(R.layout.edit_sex_dialog,null);

                String str[] = new String[2];
                str[0] = "男";
                str[1] = "女";
                new AlertDialog.Builder(this)
                        .setTitle("选择性别")
                        .setSingleChoiceItems(str, 0, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0)
                                    sex.setText("男");
                                else
                                    sex.setText("女");
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create()
                        .show();

                break;
            case R.id.set_personalbirth:
                new AlertDialog.Builder(this)
                        .setTitle("选择出生年月");
                setBir.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View source) {
                        Calendar c = Calendar.getInstance();
                        new DatePickerDialog(PersonalInfoActivity.this,
                                new DatePickerDialog.OnDateSetListener() {
                                    @Override
                                    public void onDateSet(DatePicker dp, int year, int month, int dayOfMonth) {
                                        bir.setText(+year + "年" + (month + 1) + "月" + dayOfMonth + "日");
                                    }
                                }
                                , c.get(Calendar.YEAR)
                                , c.get(Calendar.MONTH)
                                , c.get(Calendar.DAY_OF_MONTH)).show();


                    }
                });
                break;


            case R.id.set_personalphone:
                final LinearLayout layout1 = (LinearLayout) getLayoutInflater().inflate(R.layout.edit_phone_dialog, null);

                new AlertDialog.Builder(this)
                        .setIcon(null)
                        .setView(layout1)
                        .setTitle("编辑电话号码")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                EditText  tvphone = (EditText)layout1.findViewById(R.id.edit_phone);
                                final String p = tvphone.getText().toString().trim();
                                tell.setText(p);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create()
                        .show();

                break;


            case R.id.set_personalintroduce:
                final LinearLayout layout2 = (LinearLayout) getLayoutInflater().inflate(R.layout.edit_introduce_dialog, null);

                new AlertDialog.Builder(this)
                        .setIcon(null)
                        .setTitle("编辑个人介绍")
                        .setView(layout2)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                EditText tvind = (EditText)layout2.findViewById(R.id.edit_introduce);
                                final String intro = tvind.getText().toString().trim();
                                introduce.setText(intro);
                            }


                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create()
                        .show();
                break;


        }
    }




    //从本地相册选取图片作为头像
    private void choseHeadImageFromGallery()
    {
        Intent intentFromGallery = new Intent();
        //设置文件类型
        intentFromGallery.setType("image/*");
        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intentFromGallery,CODE_GALLERY_REQUEST);
    }


    private void choseHeadImageFromCameraCapture()
    {
        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        //判断存储卡是否可用，存储照片文件
        if(hasSdcard()){
            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile
                    (new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)));
        }
        startActivityForResult(intentFromCapture,CODE_CAMERA_REQUEST);


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if (isChanged) {
                Intent intent2 = new Intent();
                intent2.putExtra("name", name.getText().toString().trim());
                intent2.putExtra("personInfo", dataString);
                setResult(RESULT_OK, intent2);
            } else {
                setResult(RESULT_CANCELED);
            }
            PersonalInfoActivity.this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    //裁剪原始的图片
    public void cropRawPhoto(Uri uri)
    {
        Intent intent = new Intent ("com.android.camera.action.CROP");
        intent.setDataAndType(uri,"image/*");

        //设置裁剪
        intent.putExtra("crop","true");

        //aspectX,aspectY 宽高的比例
        intent.putExtra("aspectX",1);
        intent.putExtra("aspectY",1);

        //outputX,outputY :裁剪图片的宽高
        intent.putExtra("outputX",outPut_X);
        intent.putExtra("outputY",outPut_Y);
        intent.putExtra("return-data", true);
        startActivityForResult(intent,CODE_RESULT_REQUEST);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_CANCELED)
          {
            Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
            return;
          }
        switch(requestCode)
            {
                case CODE_GALLERY_REQUEST:
                    cropRawPhoto(intent.getData());
                    break;
                case CODE_CAMERA_REQUEST:
                    if(hasSdcard())
                    {
                        File tempFile = new File(Environment.getExternalStorageDirectory(),IMAGE_FILE_NAME);
                        cropRawPhoto(Uri.fromFile(tempFile));
                    }else
                    {
                        Toast.makeText(getApplication(),"没有SD卡",Toast.LENGTH_LONG).show();
                    }
                    break;
                case CODE_RESULT_REQUEST:
                    if(intent != null)
                        setImageToHeadView(intent);
                    break;
            }


        }


    //提取保存裁剪之后的图片数据，并设置头像部分的View
    public void setImageToHeadView(Intent intent)
    {
        Bundle extras = intent.getExtras();
        if(extras !=null)
        {
            Bitmap photo = extras.getParcelable("data");
            headImage.setImageBitmap(photo);
        }
    }

    //检查设备是否存在sd卡的工具方法
    public static boolean hasSdcard()
    {
        String state = Environment.getExternalStorageState();
        if(state.equals(Environment.MEDIA_MOUNTED))
            //有存储的SD card
            return true;
        else
            return false;
    }







    }

